package com.doyens.reggie.commons;

import com.doyens.reggie.exception.CustomException;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.sql.SQLIntegrityConstraintViolationException;

@ControllerAdvice(annotations = {Controller.class, RestController.class})
@ResponseBody
public class ProjectExceptionHandler {
    @ExceptionHandler(DuplicateKeyException.class)
    public R<String> doNullPointerException(DuplicateKeyException e){
        String message = e.getMessage();
        if(message.contains("Duplicate entry")){
            message = message.substring(message.indexOf("Duplicate entry"));
            return R.error(message.split(" ")[2]+"不能重复");// code=0 msg:发生了空指针异常 data:null
        }
        return R.error("发生了其他的未知异常");
    }

    /**
     * 异常处理方法
     * @return
     */
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> exceptionHandler(SQLIntegrityConstraintViolationException ex){
        if(ex.getMessage().contains("Duplicate entry")){
            String[] split = ex.getMessage().split(" ");
            String msg = split[2] + "已存在";
            return R.error(msg);
        }
        return R.error("未知错误");
}



    @ExceptionHandler(Exception.class)
    public R<String> doException(Exception e){
        e.printStackTrace();
        return R.error("发生了其他的未知异常");
    }

    @ExceptionHandler(CustomException.class)
    public R<String> doCustomException(CustomException e){
        return R.error(e.getMessage());
    }


}
